package com.tsd.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.tsd.CommonMsgNameConstants;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.PageBean;
import com.tsd.service.BaseServiceImpl;
import com.tsd.system.dao.SysDataLogMapper;
import com.tsd.system.entity.SysDataLog;
import com.tsd.system.entity.SysDataLogExt;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.service.SysDataLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 描述：SysDataLog 服务实现层
 *
 * @author Hillpool
 * @date 2021/01/12 12:04:12
 */
@Service
public class SysDataLogServiceImpl extends BaseServiceImpl implements SysDataLogService {

    @Resource
    private SysDataLogMapper sysDataLogMapper;

    @Override
    public SysDataLogExt getSysDataLogBySid(String sid) throws Exception {
        return sysDataLogMapper.selectBySid(sid);
    }

    @Override
    public SysDataLogExt queryBySid(String sid) throws Exception {
        return sysDataLogMapper.selectBySid(sid);
    }

    @Override
    public void deleteSysDataLog(List<String> list, SysUserExt opUser) throws Exception {
        for (String sid : list) {
            SysDataLog old = sysDataLogMapper.selectBySid(sid);
            super.checkEmpty(old, CommonMsgNameConstants.ERROR_MSG_RECORD_NOT_EXISTS);
            super.autoInjectBaseData(old, opUser, this.TYPE_DELETE);
            sysDataLogMapper.updateByPrimaryKeySelective(old);
        }
    }

    @Override
    public void saveSysDataLog(SysDataLogExt record, SysUser opUser) throws Exception {
        if (HlpUtils.isEmpty(record.getId())) {
            super.autoInjectBaseData(record, opUser, this.TYPE_CREATE);
            sysDataLogMapper.insertSelective(record);
        } else {
            super.autoInjectBaseData(record, opUser, this.TYPE_UPDATE);
            sysDataLogMapper.updateByPrimaryKeySelective(record);
        }
    }

    @Override
    public void addSysDataLog(String op_name, Object prevData, Object postData, SysUser opUser) throws Exception {
        SysDataLogExt logExt = new SysDataLogExt();
        logExt.setOp_name(op_name);
        if (!HlpUtils.isEmpty(prevData)) {
            logExt.setPrev_data(JSON.toJSONString(prevData));
        }
        if (!HlpUtils.isEmpty(postData)) {
            logExt.setPost_data(JSON.toJSONString(postData));
        }
        this.saveSysDataLog(logExt, opUser);
    }

    @Override
    public List<SysDataLogExt> findSysDataLogs(Map<String, Object> params, PageBean page) throws Exception {
        return sysDataLogMapper.selectByPage(params, page);
    }

    @Override
    public List<SysDataLogExt> findSysDataLogs(Map<String, Object> params) throws Exception {
        return sysDataLogMapper.selectByParams(params);
    }
}
